import requests
import time
import json
import os
import logging
import sys

file_path = 'testing.json'

# 验证json数据
def check_data(res_arr):

	method = ['GET','POST','OPTIONS','HEAD','PUT','PATCH','DELETE']
	enctype = ['multipart/form-data','application/json']

	err_info = "json data err index ";

	for key,val in enumerate(res_arr):	

		# 值是否存在,是否为空,类型是否正确
		if not 'api_id' in val or not isinstance (val['api_id'],str) or len(val['api_id'].strip()) == 0:
			return err_info + str(key) + " is api_id"

		if not 'host' in val or not isinstance (val['host'],str) or len(val['host'].strip()) == 0:
			return err_info + str(key) + " is host"

		if not 'method' in val or not isinstance (val['method'],str) or len(val['method'].strip()) == 0:
			return err_info + str(key) + " is method"

		if not 'enctype' in val or not isinstance (val['enctype'],str) or len(val['enctype'].strip()) == 0:
			return err_info + str(key) + " is enctype"

		if 'header' in val and not isinstance (val['header'],dict):
			return err_info + str(key) + " is header"

		if 'body' in val and not isinstance (val['body'],dict):
			return err_info + str(key) + " is body"

		# 值是否合法
		if not val['method'].strip() in method:
			return err_info + str(key) + " is method"

		if not val['enctype'].strip() in enctype:
			return err_info + str(key) + " is enctype"

	return True


# 脚本开始时间
total_start_time = int(round(time.time() * 1000))

# 打开文件
try:
	file_object = open(file_path,'r')
except Exception as e:
	print("open " + str(file_path) + " fail")
	sys.exit()

# 读取文件
try:
	file_res = file_object.read()	
except Exception as e:	
	print("read " + str(file_path) + " fail")
	sys.exit()

# 文件为空
if len(file_res.strip()) == 0:
	print("get " + str(file_path) + " content fail")
	sys.exit()

# 解析json
try:
	res_arr = json.loads(file_res)
except Exception as e:	
	print("loads " + str(file_path) + " fail")
	sys.exit()

# 数据校验
check_res = check_data(res_arr)

# 校验通过
if not check_res == True:
	print(check_res)
	sys.exit()

# 文件路径
res_file_path = "testing_res_" + str(time.strftime('%Y%m%d%H%M%S', time.localtime())) + ".json"
# 保存结果
resStr = ''
# 请求成功数
success = 0

for key,val in enumerate(res_arr):

	try:
		# 请求头
		if 'header' in val:
			header = val['header']
		else:
			header = {}

		# 请求体		
		if 'body' in val:
			body = val['body']
		else:
			body = {}

		# 请求地址
		host = val['host'].strip()
		# 编码格式
		enctype = val['enctype'].strip()
		# 请求方式
		method = val['method'].strip()
		# ID
		api_id = val['api_id'].strip()

		# 开始时间
		start_time = int(round(time.time() * 1000))
		
		# form-data格式
		if enctype == 'multipart/form-data':
			# 发送请求
			res = requests.request(method, host, headers=header, data=body,timeout=(5,10))
		# application/json格式	
		if enctype == 'application/json':
			# 请求头中添加application/json
			header_enctype = {"Content-Type":"application/json"}
			header.update(header_enctype) 
			res = requests.request(method, host, headers=header, data=json.dumps(body),timeout=(5,5))

		# 结束时间
		end_time = int(round(time.time() * 1000))
		use_time = end_time - start_time

		# 请求成功
		if res.status_code == 200:

			success = success + 1

			# 返回结果
			request_res = {"api_id":api_id, "status_code":res.status_code,"use_time":str(use_time)+"ms","res_data":res.text}

			print("--------------------")
			print("api_id: " + str(api_id))
			print("status_code: " + str(res.status_code))
			print("use_time: " + str(use_time) + 'ms')
			print("res_data: " + str(res.text))	

		else:

			# 返回结果
			request_res = {"api_id":api_id, "status_code":res.status_code,"use_time":str(use_time)}

			print("--------------------")
			print("api_id: " + str(api_id))
			print("status_code: " + str(res.status_code))
			print("use_time: " + str(use_time) + 'ms')

		resStr = resStr + str(request_res) + "\n"

	except Exception as e:

		# 返回结果
		request_res = {"api_id":api_id, "status_code":"fail"}

		print("--------------------")
		print("api_id: " + str(api_id))
		print("status_code: fail")

		resStr = resStr + str(request_res) + "\n"
		continue	
		
# 完成	
print("--------------------")
# 脚本结束时间
total_end_time = int(round(time.time() * 1000))
total_use_time = total_end_time - total_start_time
print("Testing complete")
print("request total: " + str(len(res_arr)))
print("request success: " + str(success))
print("use time: " + str(total_use_time) + "ms")

# 记录结果
with open(res_file_path, 'a') as file:
	size = file.write(str(resStr))
	if size > 0 :
		print("testing res is " + str(res_file_path))
	else:
		print("testing res write fail")

	file.close()
		